<template>
    <div class="app-container">

        <el-table :key="tableKey" :data="list" fit highlight-current-row>
            <el-table-column label="社区名" prop="name" align="center" />
            <el-table-column label="社区地址" prop="address" align="center" />
            <el-table-column label="负责人" prop="principalName" align="center" />
            <!-- 关联设备展示数量 -->

            <el-table-column label="创建时间" prop="createdAt" align="center" />

            <el-table-column label="操作" align="center" width="500px">
                <template slot-scope="{ row }">
                    <el-button v-waves type="primary" @click="updateBuilding(row.id)">编辑</el-button>
                    <!-- <el-button v-waves type="primary" @click="importBatchBuild(row.id)">批量导入</el-button> -->
                    <el-upload style="margin-right: 190px; float: right" :action="uploadPath(row.id)" :headers="headers" :on-success="handleExcelSuccess" :on-error="handleExcelError" :show-file-list="false" :accept="accept">
                        <el-button type="primary">批量导入楼层</el-button>
                        <div slot="tip" class="el-upload__tip"></div>
                    </el-upload>
                </template>
            </el-table-column>
        </el-table>
        <!-- {{ curType }} {{ newObj.parentId }} -->
        <!--打开抽屉开始  -->
        <el-drawer title="楼宇" :visible.sync="drawer" size="40%">
            <!--获取此楼宇的相关数据并且展示-->
            <template>
                <el-table :data="buildingList" style="width: 100%" :show-header="false" @row-click="clickBuild">
                    <el-table-column align="center" prop="name" label="楼层" />
                    <el-table-column prop="principalName" :formatter="pNameFormat" label="负责人" />
                </el-table>
            </template>

            <el-button style="width: 100%  ;height :40px" @click="addBuilding">+</el-button>

            <div>
                <!-- :before-close="handleClose"  关闭前的函数先关掉-->
                <!-- 单元展示框-->
                <el-drawer size="37%" title="单元" :append-to-body="true" :visible.sync="unitDrawer" :before-close="handleCloseUnit">
                    <!--单元的表格-->
                    <template>
                        <el-table :data="unitList" style="width: 100%" :show-header="false" @row-click="clickUnit">
                            <el-table-column align="center" prop="name" label="单元">
                            </el-table-column>
                            <el-table-column prop="principalName" :formatter="pNameFormat" label="负责人">
                            </el-table-column>
                        </el-table>
                    </template>
                    <el-button style="width: 100%  ;height :40px" @click="addBuilding">+</el-button>

                    <!--楼层展示框-->
                    <div>
                        <el-drawer size="34%" title="楼层" :append-to-body="true" :visible.sync="floorDrawer" :before-close="handleCloseFloor">
                            <template>
                                <el-table :data="floorList" style="width: 100%" :show-header="false" @row-click="clickFloor">
                                    <el-table-column align="center" prop="name" label="楼层">
                                    </el-table-column>
                                    <el-table-column prop="principalName" :formatter="pNameFormat" label="负责人">
                                    </el-table-column>
                                </el-table>
                            </template>
                            <el-button style="width: 100%  ;height :40px" @click="addBuilding">+</el-button>
                            <!--房间展示框-->
                            <div>
                                <el-drawer size="31%" title="房间" :append-to-body="true" :visible.sync="roomDrawer" :before-close="handleCloseRoom">
                                    <template>
                                        <el-table :data="roomList" style="width: 100%" :show-header="false">
                                            <el-table-column align="center" prop="name" label="楼层">
                                            </el-table-column>
                                            <el-table-column prop="roomType" :formatter="roomTypeFormat" label="负责人">
                                            </el-table-column>
                                        </el-table>
                                    </template>
                                    <el-button style="width: 100%  ;height :40px" @click="addBuilding">+</el-button>
                                </el-drawer>
                            </div>
                        </el-drawer>
                    </div>
                </el-drawer>
            </div>
        </el-drawer>
        <!--打开抽屉结束-->

        <!--打开创建/编辑楼宇抽屉开始  -->
        <el-drawer :title="createOrUpdateTitle" :visible.sync="createOrUpdateDrawer" size="40%">
            <!-- {{ newObj }} -->

            <!-- <el-button style="margin-left: 35rem;" type="danger" @click="cleanAll()"
        >清除所有</el-button
      > -->
            <div style="margin-top: 40px;">
                <el-form :model="newObj" ref="dataForm" :inline="true" class="demo-form-inline" v-for="(domain, index) in newObj.newObjArr" :key="domain.key">

                    <el-form-item :label="curLabel" :prop="'newObjArr.' + index + '.name'" :rules="{
                        required: true,
                        message: message,
                        trigger: 'blur'
                        }">
                        <el-input v-model="domain.name"></el-input>
                    </el-form-item>
                    <!--其他的都是负责人-->
                    <el-form-item v-if="curType == 1 || curType == 2 || curType == 3" label="负责人" :prop="'newObjArr.' + index + '.principalId'" :rules="{
                        required: true,
                        message: '负责人不能为空',
                        trigger: 'blur'
                         }">
                        <el-select v-model="domain.principalId" placeholder="请选择负责人">
                            <el-option v-for="item in principalList" :key="item.id" :label="item.name" :value="item.id" :disabled="item.disabled"></el-option>
                        </el-select>
                    </el-form-item>

                    <!--此时是选择房间 所以是选择类型-->
                    <el-form-item v-else-if="curType == 4" label="类型" :prop="'newObjArr.' + index + '.roomType'" :rules="{
                            required: true,
                            message: '类型不能为空',
                            trigger: 'blur'
                            }">
                        <el-select v-model="domain.roomType" placeholder="请选择类型">
                            <el-option label="住户" value="1"></el-option>
                            <el-option label="电梯" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="add">+</el-button>
                        <el-button :type="cutType(domain)" @click="cut(index, domain)">-</el-button>
                        <el-button @click="up(index)">↑</el-button>
                        <el-button @click="down(index)">↓</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div style="text-align: center">
                <el-button @click="submitNewObj" type="primary">提交</el-button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <el-button @click="createOrUpdateDrawer = false" type="info">取消</el-button>
            </div>
        </el-drawer>
        <!--打开创建楼宇抽屉结束  -->
    </div>
</template>

<script>
import {
    communityListByUser,
    getBuiByParentId,
    getPrincipal,
    createBuildings,
    importBatchBuild
} from "@/api/community/building/building.js";
import { getToken, getTokenName } from "@/utils/auth";
import { upload } from "@/api/common/index.js";
import waves from "@/directive/waves"; // Waves directive
import { SSL_OP_LEGACY_SERVER_CONNECT } from "constants";
export default {
    name: "LogTable",
    directives: { waves },
    filters: {},

    data() {
        return {
            createOrUpdateTitle: "xxxx",
            curLabel: "惺惺惜惺惺想寻",
            drawer: false,
            unitDrawer: false,
            floorDrawer: false,
            roomDrawer: false,
            buildingList: [], //楼层的list
            unitList: [], //单元的list
            floorList: [], // 楼层的list
            roomList: [], //房间的list
            curType: "", // 当前卡项 0:社区, 1:楼宇, 2:单元, 3:层, 4:房间
            tableKey: 0,
            principalList: [], //负责人数组
            list: [],
            buildId: "", //打开楼宇的id
            unitId: "", //打开单元的id
            floorId: "", //打开楼层的id
            createOrUpdateDrawer: false, //创建或者修改的 drawer
            newObj: {
                parentId: "",
                newObjArr: [
                    {
                        id: "", //数据主键 ,如果为空说明是新增的
                        name: "", //名字
                        principalId: "", //负责人
                        sort: "", //当前数据的的排序
                        roomType: "", //房间 类型 1住户  2电梯
                        isHasChild: "" //是否有子项,如果有就不允许被删除
                    }
                ] //需要添加的对象数组.
            },
            rules: {},
            message: "",

            //以下是关于文件上传的
            headers: {},
            accept:
                "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" //限制文件类型
        };
    },

    //监听事件
    watch: {
        curType(newValue, oldValue) {
            if (newValue == 1) {
                this.createOrUpdateTitle = "创建/编辑楼宇";
                this.curLabel = "楼名";
                this.message = "楼名不能为空";
            } else if (newValue == 2) {
                this.createOrUpdateTitle = "创建/编辑单元";
                this.curLabel = "单元名";
                this.message = "单元名不能为空";
            } else if (newValue == 3) {
                this.createOrUpdateTitle = "创建/编辑层";
                this.curLabel = "层名";
                this.message = "层名不能为空";
            } else if (newValue == 4) {
                this.createOrUpdateTitle = "创建/编辑房间";
                this.curLabel = "房间名";
                this.message = "房间名不能为空";
            }
        }
    },
    created() {
        this.headers[getTokenName()] = getToken();
        this.getList();
        this.getPrincipal(); //获取所有的负责人
    },
    methods: {
        //导入文件
        uploadPath(id) {
            return importBatchBuild(id);
        },

        //导入成功
        handleExcelSuccess(response, file, fileList) {
            //导入成功
            if (response.code !== 0) {
                this.$message.error(response.msg);
            } else {
                var repData = response.data;
                this.getList();
                if (repData.length > 0) {
                    this.$message.error(repData);
                } else {
                    //刷新当前列表
                    this.$message("导入成功");
                }
            }
        },

        //导入失败
        handleExcelError() {
            this.$message("导入失败");
            //导入失败了
        },

        //提交
        submitNewObj() {
            //校验是否存相同的数据
            var temArr = this.newObj.newObjArr;
            var temNameArr = [];
            for (let i = 0; i < temArr.length; i++) {
                temNameArr.push(temArr[i].name);
            }
            if (this.isRepeat(temNameArr)) {
                this.$message("操作失败,不允许有相同的名");
                return;
            }

            //取出所有的名字

            //循环校验数据合法性
            var checkResult = true;
            var validateArr = this.$refs["dataForm"];

            validateArr.forEach(item => {
                return new Promise((resolve, reject) => {
                    item.validate(valid => {
                        if (valid) {
                            resolve(true);
                        } else {
                            checkResult = false;
                            resolve(false);
                        }
                    });
                });
            });

            //2 提交数据
            if (checkResult) {
                //暂时不需要提示了 直接干干掉
                // this.$confirm("创建后不可删除（可修改），请核实信息真实性", "", {
                //   confirmButtonText: "确定",
                //   cancelButtonText: "取消"
                // }).then(() => {
                createBuildings(this.newObj)
                    .then(res => {
                        //关闭当前的 dialog  . //获取不到 返回的值
                        getBuiByParentId(this.newObj.parentId).then(
                            response => {
                                //赋值,,不同的 type  给不同的赋值
                                var thisType = this.curType;
                                if (thisType == 1) {
                                    this.buildingList = response;
                                } else if (thisType == 2) {
                                    this.unitList = response;
                                } else if (thisType == 3) {
                                    this.floorList = response;
                                } else if (thisType == 4) {
                                    this.roomList = response;
                                }
                            }
                        );
                        this.createOrUpdateDrawer = false;
                        //查询数据
                    })
                    .catch(err => {
                        //出错了,, 获取重新获取当前页面的信息
                        this.addBuilding();
                        console.log(err);
                    });
                //
            }
        },

        //点击楼宇某一列,,打开单元编辑的窗口
        clickBuild(row) {
            // 查询单元list
            var curRowId = row.id;
            this.unitDrawer = true;
            getBuiByParentId(curRowId).then(response => {
                this.unitList = response;
            });
            this.curType = 2;
            this.newObj.parentId = curRowId;
            this.unitId = curRowId; //当前单元的父id
        },

        //点击单元的某一列,,打开楼层的编辑窗口
        clickUnit(row) {
            var curRowId = row.id;
            //打开楼层编辑的
            this.floorDrawer = true;
            //查询 楼层的list ;
            getBuiByParentId(curRowId).then(response => {
                this.floorList = response;
            });
            this.curType = 3;
            this.newObj.parentId = curRowId;
            this.floorId = curRowId;
        },

        //点击了楼层的某一列,,打开房间的编辑窗口
        clickFloor(row) {
            var curRowId = row.id;
            //打开房间编辑的窗口
            this.roomDrawer = true;
            //查询 楼层的list ;
            getBuiByParentId(curRowId).then(response => {
                this.roomList = response;
            });
            this.curType = 4;
            this.newObj.parentId = curRowId;
        },

        //关闭单元之前的操作
        handleCloseUnit(done) {
            this.curType = 1;
            this.newObj.parentId = this.buildId;
            done();
        },
        //关闭楼层之前的操作
        handleCloseFloor(done) {
            this.curType = 2;
            this.newObj.parentId = this.unitId;
            done();
        },
        //关闭楼层之前的操作
        handleCloseRoom(done) {
            this.curType = 3;
            this.newObj.parentId = this.floorId;
            done();
        },

        //添加楼宇
        addBuilding() {
            //打开创建编辑的窗口
            this.createOrUpdateDrawer = true;
            //根据 父id查询 对应的儿子并且赋值
            var pId = this.newObj.parentId;
            getBuiByParentId(pId).then(response => {
                var curBuidArr = response;
                //先清空newObj.newObjArr,再赋值给newObject
                this.newObj.newObjArr = [];
                if (curBuidArr != null && curBuidArr.length > 0) {
                    for (let i = 0; i < curBuidArr.length; i++) {
                        this.newObj.newObjArr.push({
                            name: curBuidArr[i].name,
                            principalId: curBuidArr[i].principalId,
                            id: curBuidArr[i].id,
                            sort: curBuidArr[i].sort,
                            roomType: curBuidArr[i].roomType.toString(),
                            isHasChild: curBuidArr[i].isHasChild
                        });
                    }
                } else {
                    //空的给第一行,不然没有值很难看
                    this.add();
                }
            });
            //清空校验规则
            var validateArr = this.$refs["dataForm"];

            if (validateArr != null && validateArr.length > 0) {
                for (let i = 0; i < validateArr.length; i++) {
                    validateArr[i].clearValidate();
                }
            }
        },

        //打开编辑楼宇的盒子
        updateBuilding(id) {
            this.drawer = true;
            this.newObj.parentId = id;
            this.curType = 1; // 此时是楼宇相关的,,所以关于编辑添加都是楼宇相关的
            this.buildId = id; //赋值,如果关闭了parentId 就能找到他了
            getBuiByParentId(id).then(response => {
                this.buildingList = response;
            });
        },

        // 根据父id获取楼宇信息相关的信息
        // getBuiByParentId(id) {
        //   getBuiByParentId(id).then(response => {
        //     this.buildingList = response;
        //   });
        // },

        /**
         * 数组元素交换位置 , sort元素不变
         * @param {array} arr 数组
         * @param {number} index1 添加项目的位置
         * @param {number} index2 删除项目的位置
         * index1和index2分别是两个数组的索引值，即是两个要交换元素位置的索引值，如1，5就是数组中下标为1和5的两个元素交换位置,但是sort元素位置不变
         */
        swapArray(arr, index1, index2) {
            arr[index1] = arr.splice(index2, 1, arr[index1])[0];
            // 数组元素交换
            var tempSort = arr[index1].sort;
            arr[index1].sort = arr[index2].sort;
            arr[index2].sort = tempSort;
            return arr;
        },

        //下降
        down(index) {
            if (index == this.newObj.newObjArr.length - 1) {
                this.$message({
                    message: "已经处于底端，无法下移",
                    type: "warning",
                    duration: "1200" //显示1.5秒足矣
                });
                return;
            }
            //上下交换位置
            this.swapArray(this.newObj.newObjArr, index, index + 1);
        },
        //上升
        up(index) {
            //第一行没法再上移了
            if (index == 0) {
                this.$message({
                    message: "已经处于置顶，无法上移",
                    type: "warning",
                    duration: "1200" //显示1.5秒足矣
                });
                return;
            }
            //上下交换位置
            this.swapArray(this.newObj.newObjArr, index, index - 1);
        },
        //减当前列
        cut(index, domain) {
            if (domain.isHasChild) {
                //有孩子不能删除
                this.$message({
                    message: "此数据有子数据,不能被删除",
                    type: "warning",
                    duration: "1200" //显示1.5秒足矣
                });
                return;
            }
            //此举表示第一个数据无法移除
            if (this.newObj.newObjArr.length == 1) {
                //如果是第一条 只移除数加减
                this.$message({
                    message: "请保留最少一条数据",
                    type: "warning",
                    duration: "1200" //显示1.5秒足矣
                });
                return;
            }

            if (index !== -1) {
                this.newObj.newObjArr.splice(index, 1);
            }
        },
        //往数组里面添加新的列  ,如果是空的给sort排序为第一,如果不是就获取
        //数组最后一个元素的sort +1  等于当前的sort
        //如果是  123 roomType 给默认值-1,如果是4 principalId 给默认值 -1
        add() {
            var thisObjArr = this.newObj.newObjArr;
            var thisType = this.curType;
            var principalId = "";
            var roomType = "";
            if (thisType == 1 || thisType == 2 || thisType == 3) {
                roomType = -1;
            } else if (thisType == 4) {
                principalId = -1;
            }

            if (thisObjArr == null || thisObjArr.length == 0) {
                thisObjArr.push({
                    name: "",
                    principalId: principalId,
                    roomType: roomType,
                    sort: 1,
                    isHasChild: false
                });
            } else {
                //获取最后一家的位置
                var curSort = thisObjArr[thisObjArr.length - 1].sort;
                console.log(curSort);
                thisObjArr.push({
                    name: "",
                    principalId: principalId,
                    roomType: roomType,
                    sort: curSort + 1,
                    isHasChild: false
                });
            }
        },

        //判断数组是否有重复的元素
        isRepeat(arr) {
            var hash = {};
            for (var i in arr) {
                if (hash[arr[i]]) {
                    return true;
                } // 不存在该元素，则赋值为true，可以赋任意值，相应的修改if判断条件即可

                hash[arr[i]] = true;
            }
            return false;
        },

        //加载首页数据
        getList() {
            communityListByUser(this.listQuery).then(response => {
                this.list = response;
            });
        },

        //获取所有的负责人
        getPrincipal() {
            getPrincipal().then(response => (this.principalList = response));
        },

        // 解析负责人
        pNameFormat(row) {
            return "负责人:" + row.principalName;
        },

        roomTypeFormat(row) {
            var rtName = "";
            var rowRoomType = row.roomType;
            //1住户 2电梯
            if (rowRoomType == 1) {
                rtName = "住户";
            } else if (rowRoomType == 2) {
                rtName = "电梯";
            }
            return "类型:" + rtName;
        },

        cutType(domain) {
            if (domain.isHasChild) {
                return "warning";
            } else {
                return "";
            }
        },

        //是否展示

        //关闭之前的函数
        handleClose(done) {
            this.$confirm("还有未保存的工作哦确定关闭吗？")
                .then(_ => {
                    done();
                })
                .catch(_ => {});
        }
    }
};
</script>
<!-- 使用抽屉加上下拉-->
<style >
.el-drawer.rtl {
    overflow: scroll;
}
</style>
